package com.zero2oneit.mall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zero2oneit.mall.common.bean.member.*;
import com.zero2oneit.mall.common.query.member.PrizeRecordQueryObject;
import com.zero2oneit.mall.common.query.member.PrizeRuleQueryObject;
import com.zero2oneit.mall.common.utils.R;
import com.zero2oneit.mall.common.utils.bootstrap.BoostrapDataGrid;
import com.zero2oneit.mall.member.dto.PrizeDTO;
import com.zero2oneit.mall.member.service.*;
import org.elasticsearch.common.util.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.zero2oneit.mall.member.mapper.PrizeRecordMapper;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @author Tg
 * @email zero2oneit@163.com
 * @date 2021-05-25
 */
@Service
public class PrizeRecordServiceImpl extends ServiceImpl<PrizeRecordMapper, PrizeRecord> implements PrizeRecordService {

    @Autowired
    private PrizeRecordMapper prizeRecordMapper;

    @Autowired
    private MemberAccountsService accountsService;

    @Autowired
    private PrizeWinService winService;

    @Autowired
    private PrizeRuleService ruleService;

    @Autowired
    private PrizeWinMappingService prizeWinMappingService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public BoostrapDataGrid pageList(PrizeRecordQueryObject qo) {
        //查询总记录数
        int total = prizeRecordMapper.selectTotal(qo);
        return new BoostrapDataGrid(total, total == 0 ? Collections.EMPTY_LIST : prizeRecordMapper.selectRows(qo));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R draw(PrizeDTO prizeDTO) {
        Object accountObj = redisTemplate.opsForHash().get("om:member:accounts", prizeDTO.getMemberId());
        if(accountObj == null){
            QueryWrapper<MemberAccounts> wrappers = new QueryWrapper();
            wrappers.eq("member_id", prizeDTO.getMemberId());
            MemberAccounts accounts = accountsService.getOne(wrappers);
            redisTemplate.opsForHash().put("om:member:accounts", prizeDTO.getMemberId(), JSON.toJSONString(accounts));
        }
        MemberAccounts accounts = JSON.parseObject(accountObj.toString(), MemberAccounts.class);
        redisTemplate.opsForHash().put("om:member:accounts", prizeDTO.getMemberId(), JSON.toJSONString(accounts));

        if(accounts.getCommission().intValue() > Integer.parseInt(prizeDTO.getCommission())){
            String key = "om:member:prize";
            if (redisTemplate.hasKey(key)) {
                redisTemplate.opsForValue().increment(key, 1);
            } else {
                redisTemplate.opsForValue().set(key, String.valueOf(1));
            }
            int points = Integer.parseInt(redisTemplate.opsForValue().get(key));

            //抽奖业务处理
            //指定谁中奖
            Map<String, Object> map = new HashMap<>();
            map.put("id", 1);
            QueryWrapper<PrizeWinMapping> wraps = new QueryWrapper();
            wraps.eq("status_id", 1);
            List<PrizeWinMapping> list = prizeWinMappingService.list(wraps);
            for (PrizeWinMapping p : list) {
                if(Long.parseLong(prizeDTO.getMemberId()) == p.getMemberId()){
                    //操作中奖表
                    map.put("id", p.getPrizeId());
                    winService.save(new PrizeWin(null, Long.parseLong(prizeDTO.getMemberId()), p.getPrizeId(), 0, null, null));

                    //抽奖记录
                    prizeRecordMapper.insert(new PrizeRecord(null, Long.parseLong(prizeDTO.getMemberId()), prizeDTO.getNickName(),
                            Integer.parseInt(prizeDTO.getCommission()), null));
                    //减少金币
                    accountsService.reduce(Long.valueOf(prizeDTO.getMemberId()), Integer.parseInt(prizeDTO.getCommission()));
                    QueryWrapper<MemberAccounts> wrappers = new QueryWrapper();
                    wrappers.eq("member_id", prizeDTO.getMemberId());
                    MemberAccounts memberAccounts = accountsService.getOne(wrappers);
                    redisTemplate.opsForHash().put("om:member:accounts", prizeDTO.getMemberId(), JSON.toJSONString(memberAccounts));

                    return R.ok(map);
                }
            }

            QueryWrapper<PrizeRule> wrapper = new QueryWrapper();
            PrizeRule rule = ruleService.getOne(wrapper);
            if(points == rule.getRuleBase()){
                int randomNum = random(2, 8);
                redisTemplate.opsForValue().set(key, String.valueOf(1));
                map.put("id", randomNum);
                //操作中奖表
                winService.save(new PrizeWin(null, Long.parseLong(prizeDTO.getMemberId()),Long.valueOf(randomNum), 0, null, null));
            }

            //抽奖记录
            prizeRecordMapper.insert(new PrizeRecord(null, Long.parseLong(prizeDTO.getMemberId()), prizeDTO.getNickName(),
                     Integer.parseInt(prizeDTO.getCommission()), null));
            //减少金币
            accountsService.reduce(Long.valueOf(prizeDTO.getMemberId()), Integer.parseInt(prizeDTO.getCommission()));
            QueryWrapper<MemberAccounts> wrappers = new QueryWrapper();
            wrappers.eq("member_id", prizeDTO.getMemberId());
            MemberAccounts memberAccounts = accountsService.getOne(wrappers);
            redisTemplate.opsForHash().put("om:member:accounts", prizeDTO.getMemberId(), JSON.toJSONString(memberAccounts));

            return R.ok(map);
        }

        return R.fail("亲！您的金币不够了...请及时充值");
    }

    /**
     * 获取随机数
     * @param min
     * @param max
     * @return
     */
    public int random(int min, int max) {
        Random random = new Random();
        return random.nextInt(max)%(max-min+1) + min;
    }

}